// 大数据第八题
// author： lbc

package homework1;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class appendfile {
    public static void main(String[] args) throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        String hdfsPath = "hdfs://localhost:9000";
        FileSystem hdfs = FileSystem.get(new URI(hdfsPath), conf);
        String remotePath = "hdfstest/input.txt";
        String localPath = "/root/trash";
        String content = "append some strings";
        boolean append = true;
        if (!fileExist(hdfs, remotePath)) {
            System.err.println("file not even exist!");
        } else {
            if (append) {
                FSDataOutputStream out = hdfs.append(new Path(remotePath));
                out.write(content.getBytes());
                out.close();
                System.out.println("append to the end of the file successfully!");
            } else {
                hdfs.copyToLocalFile(new Path(remotePath), new Path(localPath));
                FSDataOutputStream out = hdfs.create(new Path(remotePath));
                out.write(content.getBytes());
                FileInputStream in = new FileInputStream(localPath);
                byte[] buf = new byte[1000];
                int read = 0;
                while ((read = in.read(buf)) > 0) {
                    out.write(buf, 0, read);
                }
                in.close();
                out.close();
                System.out.println("append to the beginning of the file");
            }
        }

        hdfs.close();
    }

    public static void touchfile(FileSystem fs, String file_path) throws IOException {
        FSDataOutputStream out = fs.create(new Path(file_path));
        out.close();
    }

    public static boolean fileExist(FileSystem fs, String file_path) throws IOException {
        return fs.exists(new Path(file_path));
    }
}
